package com.xiaopeng.common.exception;
import com.xiaopeng.common.httpResult.enums.HttpResultCodeEnum;
import lombok.Data;
import org.slf4j.helpers.MessageFormatter;

/**
 * 业务异常类，继承运行时异常，确保事务正常回滚
 * @author xiaopeng
 */
@Data
public class BusinessException extends RuntimeException {

    /**
     * 错误码
     */
    private Integer code;

    /**
     * 错误描述信息
     */
    private String message;


    private BusinessException(Integer code, String message) {
        super(message);
        this.code = code;
        this.message = message;
    }

    public static BusinessException exception(Integer code, String message) {
        BusinessException businessException = new BusinessException(code, message);
        businessException.setCode(code);
        return businessException;
    }

    public static BusinessException exception(Integer code, String message, Object... params) {
        return new BusinessException(code, format(message, params));
    }

    public static BusinessException exception(String message, Object... params) {
        return new BusinessException(HttpResultCodeEnum.FAIL.getCode(), format(message, params));
    }


    public static BusinessException exception(HttpResultCodeEnum httpResultCodeEnum) {
        return new BusinessException(httpResultCodeEnum.getCode(), httpResultCodeEnum.getMessage());
    }

    private static String format(String message, Object... params){
        return MessageFormatter.arrayFormat(message, params).getMessage();
    }

}
